package com.eques.base

import android.app.Dialog
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.eques.icvss.utils.ELog
import com.eques.service.DoorBellService
import com.eques.util.AppUtils
import com.eques.util.Config
import com.eques.util.EquesMytool
import com.eques.util.EquesPreference
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import org.json.JSONObject
import java.io.IOException

abstract class BaseActivity : BaseServiceActivity() {
    private var TAG = BaseActivity::class.java.simpleName
    lateinit var preference: EquesPreference

    var loginState: Boolean? = null
    var mContext: Context? = null
    var equesMytool: EquesMytool? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        preference = EquesPreference(this)
        equesMytool= EquesMytool(this)
        loginState = preference.getBoolean(Config.LOGIN_STATE, false)
    }


    /**
     * 设置信息函数
     *
     * 该函数通过HTTP请求向服务器发送信息，以更新特定锁的设置
     * 它从偏好设置中获取必要的用户信息和配置，构造请求URL和请求体，然后使用OkHttp客户端发送请求
     * 如果服务器返回成功响应，它会解析响应并根据情况显示成功消息
     *
     * @param str 包含要设置的信息的JSON字符串
     * @param lockId 锁的唯一标识符
     */
    fun setInfo(str: String,lockId:String) {
        // 从偏好设置中获取子地址
        var subIp = preference.getString(Config.SUB_ADDRESS)
        // 从偏好设置中获取用户令牌
        val token = preference.getString(Config.EQUES_USER_TOKEN)
        // 从偏好设置中获取用户ID
        var uid = preference.getString(Config.EQUES_USER_UID)
        // 构造请求URL
        val url = Config.shadowSettingsUpdateUrl(
            subIp!!,
            uid!!,
            token!!,
            lockId,
        )
        // 日志记录URL
        ELog.e("....url..$url")
        // 创建媒体类型，指定请求体的类型为application/json
        val mediaType: MediaType = "application/json".toMediaTypeOrNull()!!
        // 创建请求体，包含要发送的JSON字符串
        val requestBody: RequestBody = RequestBody.create(mediaType, str)
        // 创建OkHttp客户端
        val client = OkHttpClient()
        // 构建POST请求
        val request = Request.Builder()
            .url(url!!).post(requestBody)
            .build()
        // 发送请求并处理响应
        client.newCall(request).execute().use { response ->
            // 如果响应不成功，抛出异常
            if (!response.isSuccessful) throw IOException("Unexpected code $response")
            // 解析响应体为JSON对象
            val jsonObject = response.body?.string()?.let { JSONObject(it) }
            try {
                // 从JSON对象中获取状态码
                val code = jsonObject!!.optInt("code")
                // 如果状态码为0，表示设置成功
                if (code == 0) {
                    // 在主线程中运行，以显示成功消息
                    runOnUiThread{
                        showToast("设置成功")
                    }
                }
            } catch (e: Exception) {
                // 捕获并打印异常
                e.printStackTrace()
            }
        }
    }




    fun showToast(toast: String) {
        runOnUiThread{
            Toast.makeText(this, toast, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 点击重连机制
     */
    open fun userClickReconnection() {
        if (doorBellService == null) {
            ELog.d(TAG, " userClickReconnection() doorBellService is null start init...")
            doorBellService = AppUtils.service!!
        }
        if (doorBellService != null) {
            ELog.d(TAG, " userClickReconnection() login start...")
            doorBellService!!.login(DoorBellService.MSG_ONCLICK_LOGIN)
        } else {
            ELog.d(TAG, " userClickReconnection() doorBellService is null!!! ")
        }
    }

    /**
     * 用户退出登录
     * 断开socket连接
     */
    open fun AccountLogOut() {
        ELog.i(TAG, " AccountLogOut() start... ")
        if (DoorBellService.icvss != null && DoorBellService.icvss!!.equesIsLogin()) {
            doorBellService!!.userLogout()
        } else {
            ELog.d(TAG, " AccountLogOut() icvss is null error ")
        }
    }


    override fun onDestroy() {
        super.onDestroy()
    }



    abstract fun initView()

    abstract fun initData()

    /**
     * 创建加载进度条
     *
     * @param msgRes
     */
    open fun createProgressDialog(ctx: Context, msgRes: Int, showFlag: Boolean): Dialog? {
        this.mContext = ctx
        if (equesMytool == null) {
            equesMytool = EquesMytool(ctx)
        }
        return equesMytool!!.createProgressDialog(ctx, msgRes, showFlag)
    }

    /**
     * 取消加载进度条
     */
    open fun stopProgressDialog() {
        if (equesMytool == null) {
            equesMytool = EquesMytool(mContext)
        }
        equesMytool!!.stopProgressDialog()
    }



}